﻿using System;

namespace _14_Command
{
    /// <summary>
    /// 命令模式
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            //命令是一种行为设计模式， 它可将请求或简单操作转换为一个对象。
            Invoker invoker = new Invoker();
            invoker.SetOnStart(new SimpleCommand("Say Hi!"));
            Receiver receiver = new Receiver();
            invoker.SetOnFinish(new ComplexCommand(receiver, "Send email", "Save report"));
            invoker.DoSomethingImportant();
            Console.ReadKey();
        }
    }
    public interface ICommand
    {
        void Execute();
    }
    class SimpleCommand : ICommand
    {
        private string _payload = string.Empty;
        public SimpleCommand(string payload)
        {
            _payload = payload;
        }
        public void Execute()
        {
            Console.WriteLine($"SimpleCommand:See, I can do simple thing like  printing ({_payload})");

        }
    }
    class ComplexCommand : ICommand
    {
        private Receiver _receiver;
        private string _a;
        private string _b;
        public ComplexCommand(Receiver receiver,string a,string b)
        {
            _receiver = receiver;
            _a = a;
            _b = b;
        }
        public void Execute() {
            Console.WriteLine("ComplexCommand: Complex stuff should be done by a receiver object.");
            _receiver.DoSomething(_a);
            _receiver.DoSomethingElse(_b);
        }
    }
    class Receiver
    {
        public void DoSomething(string a)
        {
            Console.WriteLine($"Receiver:working on ({a})");
        }
        public void DoSomethingElse(string b)
        {
            Console.WriteLine($"Receiver:Also working on ({b})");
        }
    }
    class Invoker
    {
        private ICommand _onStart;
        private ICommand _onFinish;
        public void SetOnStart(ICommand command)
        {
            _onStart = command;
        }
        public void SetOnFinish(ICommand command)
        {
            _onFinish = command;
        }

        public void DoSomethingImportant()
        {
            Console.WriteLine("Invoker: Does anybody want something done before I begin?");
            if(_onStart is ICommand)
            {
                _onStart.Execute();
            }
            Console.WriteLine("Invoker:...doing something really important...");
            Console.WriteLine("Invoker:Does anybody want something done after I finish?");
            if(_onFinish is ICommand)
            {
                _onFinish.Execute();
            }
        }
    }
}
